//------------------------------------------------------------------------------
#include "clientconnection.h"
#include <QString>
#include <QByteArray>
//------------------------------------------------------------------------------
ClientConnection::ClientConnection(QLocalSocket *socket, QObject *parent) : QObject(parent){
	m_socket = socket;

	connect(m_socket, SIGNAL(readyRead()), this, SLOT(dataReadyToRead()));
	connect(m_socket, SIGNAL(disconnected()), this, SIGNAL(disconnected()));
}
//------------------------------------------------------------------------------
ClientConnection::~ClientConnection(){
}
//------------------------------------------------------------------------------
void ClientConnection::close(){
	m_socket->close();
	m_socket->waitForDisconnected();
}
//------------------------------------------------------------------------------
void ClientConnection::dataReadyToRead(){
	char buff[DATA_READ_BUFFER_SIZE];
	qint64 read=0;
	QByteArray data;

	while((read = m_socket->read(buff, DATA_READ_BUFFER_SIZE)) > 0){
		data.append(buff, read);
	}

	if(read == -1){
		qWarning()<<"ClientConnection::dataReadyToRead - Read failed ("<<m_socket->error()<<") "<<m_socket->errorString();
		this->close();
		emit disconnected();
		return;
	}

	if(data.length() > 0){
		STNMessage m;
		if(m.loadFromXml(data))
			emit messageReceived(m);
	}
}
//------------------------------------------------------------------------------
